//
//  kliceViewController.m
//  klice
//
//  Created by 권오상 on 11. 6. 22..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "kliceViewController.h"

@implementation kliceViewController

//@synthesize text;
//@synthesize searchBar;
//@synthesize barButtonItem;

- (void)viewDidLoad {
	//searchBar.delegate = self;
	kliceTextView.autocorrectionType = UITextAutocapitalizationTypeNone;
    [[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardWasShown:)
												 name:UIKeyboardDidShowNotification object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardWillBeHidden:)
												 name:UIKeyboardWillHideNotification object:nil];
}

-(IBAction) complete :(id)sender {
	
	
	if ([searchBar.text isEqualToString:@""]) {
		UIAlertView *Alert = [[UIAlertView alloc] 
							  initWithTitle:nil message:@"전화번호가 없습니다." 
							  delegate:self cancelButtonTitle:nil
							  otherButtonTitles:@"OK", nil];
		Alert.delegate = self;
		[Alert show];
		return;
	}
	
	if ([kliceTextView.text isEqualToString:@""]) {
		UIAlertView *Alert = [[UIAlertView alloc] 
							  initWithTitle:nil message:@"내용이 없습니다." 
							  delegate:self cancelButtonTitle:nil
							  otherButtonTitles:@"OK", nil];
		Alert.delegate = self;
		[Alert show];
		return;
	}
	
	MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
	if([MFMessageComposeViewController canSendText]){
		
		picker.messageComposeDelegate = self;
		picker.recipients = [NSArray arrayWithObject:searchBar.text];  
		picker.body = kliceTextView.text;
	
		[self presentModalViewController:picker animated:YES];
	}

	[picker release];
}

#pragma mark -
#pragma mark UIKeyboard Notification

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification {
	NSLog(@"keyboardWasShown");
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
	//CGSize tbSize = searchBar.frame.size;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    kliceTextView.contentInset = contentInsets;
    kliceTextView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
   // aRect.size.height -= tbSize.height;
    if (!CGRectContainsPoint(aRect, kliceTextView.frame.origin) ) {
		CGPoint scrollPoint = CGPointMake(0.0, kliceTextView.frame.origin.y-kbSize.height);
        [kliceTextView setContentOffset:scrollPoint animated:YES];
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification {
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    kliceTextView.contentInset = contentInsets;
    kliceTextView.scrollIndicatorInsets = contentInsets;
}

#pragma mark -
#pragma mark UITextViewDelegate methods
//몇개 method 지웠음

#define sizeOfContentWidth 1010
#define sizeOfContentHeight 1000
#define sizeOfContentLine 25
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
	//NSLog(@"shouldChangeTextInRange %i",textView.tag);
	//NSLog(@"%@", replacementText);
	
	//자소분리 기능 안써도 되겠는데?
	NSLog(@"replacementText : %@, length : %i, location : %i",text ,range.length, range.location);
	return TRUE;
}

//- (CGRect)scrollToCursor
//{
//	
//	@try {
//
//		
//		// Stores the original position of the cursor
//		NSRange originalPosition = text.selectedRange;    
//		
//		// Compute text's origin
//		CGPoint origin = text.frame.origin;
//		
//		// Check whether the right after cursor is a character
//		unichar c = ' ';
//		
//		if(text.selectedRange.location != [text.text length])
//			c = [text.text characterAtIndex:text.selectedRange.location];
//		
//		
//		
//		// If not a character, then cursor moves to the end of a word
//		if(c != 32 && c != 10){
//			NSRange delimiter = [text.text rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]
//														   options:NSLiteralSearch
//															 range:NSMakeRange(text.selectedRange.location, [text.text length] - text.selectedRange.location)];
//			
//			
//			if(delimiter.location == NSNotFound){
//				delimiter.location = [text.text length];
//			}
//			
//			text.selectedRange = delimiter;
//		}
//		
//		
//		
//		// Deviation between the original cursor location and moved location
//		int deviationLocation = text.selectedRange .location - originalPosition.location;
//		
//		
//		// Substring the part before the cursor position
//		NSString* head = [text.text substringToIndex:text.selectedRange.location];
//		
//		// Gets the size of this part
//		CGSize initialSize = [head sizeWithFont:text.font constrainedToSize:CGSizeMake(sizeOfContentWidth, sizeOfContentHeight)];
//		
//		// Gets the length of the head
//		NSUInteger startOfLine = [head length];
//		
//		
//		
//		// The first line
//		BOOL isFirstLine = NO;
//		
//		if(initialSize.height / sizeOfContentLine == 1){
//			isFirstLine = YES;
//		}
//		
//		
//		
//		
//		while (startOfLine > 0 && isFirstLine == NO) {
//			// Adjusts startOfLine to the beginning of the first word before startOfLine
//			NSRange delimiter = [head rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet] options:NSBackwardsSearch range:NSMakeRange(0, startOfLine)];
//			
//			// Updates startsOfLine
//			startOfLine = delimiter.location;
//			
//			
//			
//			
//			// Check if drawing the substring of head up to startOfLine causes a reduction in height compared to initialSize. 
//			NSString *tempHead = [head substringToIndex:startOfLine];
//			
//			// Gets the size of this temp head
//			CGSize tempHeadSize = [tempHead sizeWithFont:text.font constrainedToSize:CGSizeMake(sizeOfContentWidth, sizeOfContentHeight)];
//			
//			// Count the line of the original
//			int beforeLine = initialSize.height / sizeOfContentLine;
//			
//			// Count the line of the one after processing
//			int afterLine = tempHeadSize.height / sizeOfContentLine;
//			
//			// If so, then you've identified the start of the line containing the cursor, otherwise keep going.
//			if(beforeLine != afterLine)
//				break;
//		}
//		
//		// Substring the part after the cursor position
//		NSString* tail;
//		
//		printf("startOfLine:%d   deviationLocation:%d\n",startOfLine, deviationLocation);
//		
//		NSLog(@"--- head ---\n%@", head);
//		
//		if(isFirstLine == NO)
//			tail = [head substringFromIndex:(startOfLine + deviationLocation)];
//		else {
//			tail = [head substringToIndex:(startOfLine - deviationLocation)];
//		}
//		
//		
//		
//		// Gets the size of this part
//		CGSize lineSize = [tail sizeWithFont:text.font forWidth:sizeOfContentWidth lineBreakMode:UILineBreakModeWordWrap];
//		
//		// Gets the cursor position in coordinate
//		CGPoint cursor = origin;    
//		cursor.x += lineSize.width;
//		cursor.y += initialSize.height - lineSize.height;
//		
//		
//		// Back to the original position
//		text.selectedRange = originalPosition;
//		
//		printf("x: %f,   y: %f\n", cursor.x, cursor.y);	
//		
//		
//		
//		
//		return CGRectMake(cursor.x, cursor.y, 0, 0);
//		
//	
//		
//	}
//	@catch (NSException * e) {
//		return CGRectMake(0, 0, 0, 0);
//	}
//	@finally {
//		
//	}
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
//	
////    // if there is a selection cursor…
////    if(text.selectedRange.location != NSNotFound) {
////		
////        NSLog(@"selectedRange: %d %d", text.selectedRange.location, text.selectedRange.length);
////		
////        // work out how big the text view would be if the text only went up to the cursor
////        NSRange range;
////        range.location = text.selectedRange.location;
////        range.length = text.text.length - range.location;
////        NSString *string = [text.text stringByReplacingCharactersInRange:range withString:@""];
////        CGSize size = [string sizeWithFont:text.font 
////						 constrainedToSize:text.bounds.size 
////							 lineBreakMode:UILineBreakModeWordWrap];
////		
////        // work out where that position would be relative to the textView's frame
////        CGRect viewRect = text.frame;  
////        int scrollHeight = viewRect.origin.y + size.height - 50;
////        CGRect finalRect = CGRectMake(viewRect.origin.x + size.width, scrollHeight, 1, 1);
////		return finalRect;
////        // scroll to it
////        //[self.scrollView scrollRectToVisible:finalRect animated:YES];
////    }
////	return text.frame;
//}

- (void)textViewDidChange:(UITextView *)textView{
	NSLog(@"textView.text : %@", textView.text);
//	if (true) {
//	
//		UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"Change Color" action:@selector(changeColor:)];
//		
//		// bring up edit menu.
//		UIMenuController *theMenu = [UIMenuController sharedMenuController];
//		CGRect selectionRect = [self scrollToCursor];//CGRectMake (10, 10, 100, 20);
//		[theMenu setTargetRect:selectionRect inView:text];
//		
//		theMenu.arrowDirection = UIMenuControllerArrowLeft;
//		theMenu.menuItems = [NSArray arrayWithObject:menuItem];
//		[theMenu setMenuVisible:YES animated:YES];
//	}
}

- (void)textViewDidChangeSelection:(UITextView *)textView{
	//NSLog(@"textViewDidChangeSelection %i",textView.tag);
}

#pragma mark -
#pragma mark Text Menu Display methods

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {

	//여기서 레이아웃 조정 
    BOOL retValue = NO;
//    ColorTile *theTile = [self colorTileForOrigin:currentSelection];
	
    if (action == @selector(changeColor:) ){
//		NSLog(@"paste");
//        retValue = (theTile == nil) &&
//		[[UIPasteboard generalPasteboard] containsPasteboardTypes:
//		 [NSArray arrayWithObject:ColorTileUTI]];
		return YES;

    } else if ( action == @selector(cut:) || action == @selector(changeColor:) ) {
//		NSLog(@"cut/copy");
//        retValue = (theTile != nil);
		return NO;
	} else{
        //retValue = [super canPerformAction:action withSender:sender];
    }
	return retValue;
}

#pragma mark -
#pragma mark UIAlertViewDelegate methods

// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	//NSLog(@"aaaaaa %i", buttonIndex);
}

#pragma mark -
#pragma mark MFMessageComposeViewControllerDelegate methods

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
	NSString *message = @"";
	switch (result)
	{
		case MessageComposeResultCancelled:
			message = @"Result: canceled";
			NSLog(@"Result: canceled");
			//조용이 닫히면 됨
			break;
		case MessageComposeResultSent:
			message = @"Result: sent";
			NSLog(@"Result: sent");
			break;
		case MessageComposeResultFailed:
			message = @"Result: failed";
			NSLog(@"Result: failed");
			break;
		default:
			message = @"Result: not sent";
			NSLog(@"Result: not sent");
			break;
	}
	UIAlertView *Alert = [[UIAlertView alloc] 
						  initWithTitle:nil message:message 
						  delegate:self cancelButtonTitle:nil
						  otherButtonTitles:@"OK", nil];
	Alert.delegate = self;
	[Alert show];
	[self dismissModalViewControllerAnimated:YES];
	
}

#pragma mark -
#pragma mark ABPeoplePickerNavigationControllerDelegate methods

// Displays the information of a selected person
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
	return YES;
}


// Does not allow users to perform default actions such as dialing a phone number, when they select a person property.
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person 
								property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
   if (property == kABPersonPhoneProperty) {
        
        ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
        
        for(CFIndex i = 0; i < ABMultiValueGetCount(multiPhones); i++) {
            if(identifier == ABMultiValueGetIdentifierAtIndex (multiPhones, i)) {
                CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
                CFRelease(multiPhones);
                NSString *phoneNumber = (NSString *) phoneNumberRef;
                CFRelease(phoneNumberRef);
                searchBar.text = phoneNumber;
                //NSLog(@"phone = %@", phoneNumber);
            }
        }
    }
	
	[self dismissModalViewControllerAnimated:YES];
	return NO; //YES : 전화걸림, 메일쓰기가짐.
}


// Dismisses the people picker and shows the application when users tap Cancel. 
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker;
{
	[self dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark UISearchBarDelegate
- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchbar{
	
	ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;

	// Display could person's phone, email, and birthdate
	// but only phone number
	NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty], nil];	
	picker.displayedProperties = displayedItems;
	
	// Show the picker 
	[self presentModalViewController:picker animated:YES];
    [picker release];	
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchbar{
	[self searchBarBookmarkButtonClicked:searchbar];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

@end
